<?php

namespace App\Models;

class MoneyBook extends Model
{
    protected $table = 'money_books';

    protected $fillable = [
        'name',
        'icon',
        'description',
        'user_id', // 创建者用户ID
        'is_default', // 是否为默认账本
    ];

    public static function boot()
    {
        parent::boot();
        static::created(function ($model) {
            // 添加创建者为管理员
            MoneyBookUser::create([
                'book_id' => $model->id,
                'user_id' => $model->user_id,
                'role' => MoneyBookUser::ROLE_ADMIN,
            ]);

            // 创建默认分类
            $model->createDefaultCategories();
        });
    }

    /**
     * 创建默认分类
     */
    private function createDefaultCategories()
    {
        $bookId = $this->id;
        try {
            // 从JSON文件读取默认分类数据
            $jsonPath = storage_path('app/default_categories.txt');

            if (!file_exists($jsonPath)) {
                \Log::error('默认分类JSON文件不存在: ' . $jsonPath);
                return;
            }

            $jsonContent = file_get_contents($jsonPath);
            $defaultData = json_decode($jsonContent, true);

            if (!$defaultData || !isset($defaultData['categories'])) {
                \Log::error('默认分类JSON文件格式错误');
                return;
            }

            // 遍历所有分类
            foreach ($defaultData['categories'] as $categoryData) {
                // 创建主分类
                $category = MoneyCategory::create([
                    'book_id' => $bookId,
                    'name' => $categoryData['name'],
                    'icon' => $categoryData['icon'],
                    'type' => $categoryData['type'],
                    'sort' => $categoryData['sort'],
                    'description' => $categoryData['description'] ?? null,
                ]);

                // 创建子分类
                if (isset($categoryData['sub_categories']) && is_array($categoryData['sub_categories'])) {
                    foreach ($categoryData['sub_categories'] as $subCategoryData) {
                        MoneySubCategory::create([
                            'book_id' => $bookId,
                            'category_id' => $category->id,
                            'name' => $subCategoryData['name'],
                            'icon' => $subCategoryData['icon'],
                            'sort' => $subCategoryData['sort'],
                            'description' => $subCategoryData['description'] ?? null,
                        ]);
                    }
                }
            }

        } catch (\Exception $e) {
            \Log::error('创建默认分类失败: ' . $e->getMessage());
            // 如果JSON文件读取失败，可以选择创建基础分类或者抛出异常
            throw new \Exception('创建默认分类失败');
        }
    }

    /**
     * 获取账本创建者
     */
    public function creator()
    {
        return $this->belongsTo(User::class, 'user_id');
    }

    /**
     * 获取账本的所有用户
     */
    public function users()
    {
        return $this->belongsToMany(User::class, 'money_book_users', 'book_id', 'user_id')
                    ->withPivot('role')
                    ->withTimestamps();
    }

    /**
     * 获取账本的所有交易记录
     */
    public function transactions()
    {
        return $this->hasMany(MoneyTransaction::class, 'book_id');
    }

    /**
     * 获取账本的所有分类
     */
    public function categories()
    {
        return $this->hasMany(MoneyCategory::class, 'book_id')->orderBy('sort');
    }
}
